package com.example.backend.controller;

import com.example.backend.dto.ApiResponse;
import com.example.backend.dto.LoginRequest;
import com.example.backend.dto.LoginResponse;
import com.example.backend.dto.RegisterRequest;
import com.example.backend.dto.UserDto;
import com.example.backend.domain.entity.User;
import com.example.backend.domain.enums.Role;
import com.example.backend.service.AuthService;
import com.example.backend.service.UserService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.validation.Valid;
import org.springframework.http.ResponseEntity;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/api/auth")
@Tag(name = "认证管理", description = "用户登录和认证相关操作")
public class AuthController {
    private final AuthService authService;
    private final UserService userService;
    private final PasswordEncoder passwordEncoder;

    public AuthController(AuthService authService, UserService userService, PasswordEncoder passwordEncoder) {
        this.authService = authService;
        this.userService = userService;
        this.passwordEncoder = passwordEncoder;
    }

    @GetMapping("/users-simple")
    public ResponseEntity<ApiResponse<List<UserDto>>> getUsersSimple() {
        try {
            System.out.println("获取用户列表请求");
            List<User> users = userService.findAll();
            List<UserDto> userDtos = users.stream()
                    .map(user -> UserDto.builder()
                            .id(user.getId())
                            .username(user.getUsername())
                            .fullName(user.getFullName())
                            .email(user.getEmail())
                            .role(user.getRole().name().toLowerCase())
                            .status(user.getStatus().name())
                            .createdAt(user.getCreatedAt())
                            .updatedAt(user.getUpdatedAt())
                            .build())
                    .toList();
            return ResponseEntity.ok(ApiResponse.success("获取用户列表成功", userDtos));
        } catch (Exception e) {
            System.out.println("获取用户列表失败: " + e.getMessage());
            e.printStackTrace();
            return ResponseEntity.badRequest().body(ApiResponse.error("获取用户列表失败: " + e.getMessage()));
        }
    }

    @PostMapping("/register")
    @Operation(summary = "用户注册", description = "注册新用户账号")
    public ResponseEntity<ApiResponse<UserDto>> register(@Valid @RequestBody RegisterRequest request) {
        try {
            // 记录请求数据
            System.out.println("=== 用户注册请求开始 ===");
            System.out.println("请求时间: " + java.time.LocalDateTime.now());
            System.out.println("请求数据: " + request);
            System.out.println("用户名: " + request.getUsername());
            System.out.println("邮箱: " + request.getEmail());
            System.out.println("角色: " + request.getRole());
            System.out.println("真实姓名: " + request.getFullName());
            System.out.println("密码长度: " + (request.getPassword() != null ? request.getPassword().length() : 0));
            System.out.println("确认密码长度: " + (request.getConfirmPassword() != null ? request.getConfirmPassword().length() : 0));
            
            // 额外的业务逻辑验证
            validateRegisterRequest(request);
            
            UserDto user = authService.register(request);
            
            System.out.println("注册成功，用户ID: " + user.getId());
            System.out.println("=== 用户注册请求结束 ===");
            
            return ResponseEntity.ok(ApiResponse.success("注册成功", user));
        } catch (Exception e) {
            System.out.println("注册失败: " + e.getMessage());
            e.printStackTrace();
            System.out.println("=== 用户注册请求结束（失败） ===");
            return ResponseEntity.badRequest().body(ApiResponse.error(e.getMessage()));
        }
    }

    /**
     * 验证注册请求的额外业务逻辑
     */
    private void validateRegisterRequest(RegisterRequest request) {
        System.out.println("开始验证注册请求...");
        
        // 验证密码确认
        if (!request.getPassword().equals(request.getConfirmPassword())) {
            System.out.println("验证失败: 两次输入的密码不一致");
            throw new RuntimeException("两次输入的密码不一致");
        }
        
        // 验证用户名格式
        if (!request.getUsername().matches("^[a-zA-Z0-9_]+$")) {
            System.out.println("验证失败: 用户名格式不正确");
            throw new RuntimeException("用户名只能包含字母、数字和下划线");
        }
        
        // 验证邮箱格式
        if (!request.getEmail().matches("^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$")) {
            System.out.println("验证失败: 邮箱格式不正确");
            throw new RuntimeException("邮箱格式不正确");
        }
        
        // 验证真实姓名格式
        if (request.getFullName() != null && !request.getFullName().matches("^[\\u4e00-\\u9fa5a-zA-Z\\s]+$")) {
            System.out.println("验证失败: 真实姓名格式不正确");
            throw new RuntimeException("真实姓名只能包含中文、英文和空格");
        }
        
        // 验证角色
        try {
            Role.valueOf(request.getRole().toUpperCase());
        } catch (IllegalArgumentException e) {
            System.out.println("验证失败: 无效的用户角色 - " + request.getRole());
            throw new RuntimeException("无效的用户角色: " + request.getRole());
        }
        
        System.out.println("注册请求验证通过");
    }

    @PostMapping("/create-admin")
    @Operation(summary = "创建管理员", description = "创建默认管理员账户")
    public ResponseEntity<ApiResponse<UserDto>> createAdmin() {
        try {
            // 检查是否已存在admin用户
            if (userService.existsByUsername("admin")) {
                return ResponseEntity.ok(ApiResponse.success("管理员用户已存在", null));
            }
            
            // 创建管理员用户
            RegisterRequest request = new RegisterRequest();
            request.setUsername("admin");
            request.setPassword("admin123");
            request.setConfirmPassword("admin123");
            request.setFullName("系统管理员");
            request.setEmail("admin@example.com");
            request.setRole("ADMIN");
            
            UserDto user = authService.register(request);
            return ResponseEntity.ok(ApiResponse.success("管理员用户创建成功", user));
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(ApiResponse.error("创建管理员失败: " + e.getMessage()));
        }
    }

    @PostMapping("/login")
    @Operation(summary = "用户登录", description = "使用用户名和密码登录系统")
    public ResponseEntity<ApiResponse<LoginResponse>> login(@Valid @RequestBody LoginRequest request) {
        // 不捕获异常，让 GlobalExceptionHandler 统一处理
        // 这样可以确保错误码和HTTP状态码一致
        LoginResponse response = authService.login(request);
        return ResponseEntity.ok(ApiResponse.success("登录成功", response));
    }

    @PostMapping("/logout")
    @Operation(summary = "用户登出", description = "用户登出系统")
    public ResponseEntity<ApiResponse<Void>> logout() {
        // 简单的登出，实际项目中可能需要将token加入黑名单
        return ResponseEntity.ok(ApiResponse.success("登出成功", null));
    }

    @GetMapping("/me")
    @Operation(summary = "获取当前用户信息", description = "获取当前登录用户的详细信息")
    public ResponseEntity<ApiResponse<UserDto>> getCurrentUser(HttpServletRequest request) {
        try {
            String token = extractTokenFromRequest(request);
            UserDto user = authService.getCurrentUser(token);
            return ResponseEntity.ok(ApiResponse.success("获取用户信息成功", user));
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(ApiResponse.error(e.getMessage()));
        }
    }

    @GetMapping("/permissions")
    @Operation(summary = "获取用户权限", description = "获取当前用户的权限列表")
    public ResponseEntity<ApiResponse<List<String>>> getUserPermissions(HttpServletRequest request) {
        try {
            String token = extractTokenFromRequest(request);
            List<String> permissions = authService.getUserPermissions(token);
            return ResponseEntity.ok(ApiResponse.success("获取权限成功", permissions));
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(ApiResponse.error(e.getMessage()));
        }
    }

    @GetMapping("/roles")
    @Operation(summary = "获取所有角色", description = "获取系统中所有可用的角色")
    public ResponseEntity<ApiResponse<List<String>>> getAllRoles() {
        List<String> roles = List.of("ADMIN", "AGENT", "CUSTOMER");
        return ResponseEntity.ok(ApiResponse.success("获取角色成功", roles));
    }

    private String extractTokenFromRequest(HttpServletRequest request) {
        String bearerToken = request.getHeader("Authorization");
        if (bearerToken != null && bearerToken.startsWith("Bearer ")) {
            return bearerToken.substring(7);
        }
        throw new RuntimeException("未找到有效的认证令牌");
    }
}
